package cn.ruanyun.backInterface.modules.business.balance.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import cn.ruanyun.backInterface.common.enums.*;
import cn.ruanyun.backInterface.common.utils.*;
import cn.ruanyun.backInterface.common.vo.PageVo;
import cn.ruanyun.backInterface.modules.base.pojo.User;
import cn.ruanyun.backInterface.modules.base.service.UserService;
import cn.ruanyun.backInterface.modules.base.service.mybatis.IUserService;
import cn.ruanyun.backInterface.modules.business.balance.vo.AppBalanceVO;
import cn.ruanyun.backInterface.modules.business.balance.mapper.BalanceMapper;
import cn.ruanyun.backInterface.modules.business.balance.pojo.Balance;
import cn.ruanyun.backInterface.modules.business.balance.service.IBalanceService;
import cn.ruanyun.backInterface.modules.business.balance.vo.BalanceCountVo;
import cn.ruanyun.backInterface.modules.business.order.pojo.Order;
import cn.ruanyun.backInterface.modules.business.order.service.IOrderService;
import cn.ruanyun.backInterface.modules.business.orderAfterSale.pojo.OrderAfterSale;
import cn.ruanyun.backInterface.modules.business.orderAfterSale.service.IOrderAfterSaleService;
import cn.ruanyun.backInterface.modules.business.orderDetail.pojo.OrderDetail;
import cn.ruanyun.backInterface.modules.business.orderDetail.service.IOrderDetailService;
import cn.ruanyun.backInterface.modules.business.profitDetail.pojo.ProfitDetail;
import cn.ruanyun.backInterface.modules.business.profitDetail.service.IProfitDetailService;
import cn.ruanyun.backInterface.modules.business.profitPercent.service.IProfitPercentService;
import cn.ruanyun.backInterface.modules.business.profitPercent.vo.ProfitPercentDetailVo;
import cn.ruanyun.backInterface.modules.business.profitPercent.vo.ProfitPercentVo;
import cn.ruanyun.backInterface.modules.business.storeIncome.pojo.StoreIncome;
import cn.ruanyun.backInterface.modules.business.storeIncome.service.IStoreIncomeService;
import cn.ruanyun.backInterface.modules.business.storeIncome.vo.StoreIncomeCountVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.web.context.request.NativeWebRequest;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;


/**
 * 余额明细接口实现
 * @author zhu
 */
@Slf4j
@Service
@Transactional
public class IBalanceServiceImpl extends ServiceImpl<BalanceMapper, Balance> implements IBalanceService {


    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IStoreIncomeService storeIncomeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderAfterSaleService orderAfterSaleService;

    @Autowired
    private UserService japUserService;

    @Autowired
    private IProfitDetailService profitDetailService;

    @Autowired
    private IProfitPercentService profitPercentService;


    private final static ReentrantLock REENTRANT_LOCK = new ReentrantLock();

    volatile private static int nextOne = 1;

    private static final Condition c1 = REENTRANT_LOCK.newCondition();

    private static final Condition c2 = REENTRANT_LOCK.newCondition();

    private static final Condition c3 = REENTRANT_LOCK.newCondition();

    private static final Condition c4 = REENTRANT_LOCK.newCondition();

    private final AtomicDouble balance = new AtomicDouble(0);

    @Override
    public void insertOrderUpdateBalance(Balance balance) {

        if (ToolUtil.isEmpty(balance.getCreateBy())) {

            balance.setCreateBy(securityUtil.getCurrUser().getId());
        } else {

            balance.setUpdateBy(securityUtil.getCurrUser().getId());
        }

        Mono.fromCompletionStage(CompletableFuture.runAsync(() -> this.saveOrUpdate(balance)))
                .publishOn(Schedulers.fromExecutor(ThreadPoolUtil.getPool()))
                .toFuture().join();
    }

    @Override
    public void removeBalance(String ids) {

        CompletableFuture.runAsync(() -> this.removeByIds(ToolUtil.splitterStr(ids)));
    }

    /**
     * app 获取用户明细
     * @return List<AppBalanceVO>
     */
    @Override
    public List<AppBalanceVO> getAppBalance(PageVo pageVo) {

        return Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<Balance>lambdaQuery()
                .eq(Balance::getCreateBy, securityUtil.getCurrUser().getId())
                .orderByDesc(Balance::getCreateTime))))
        .map(balances -> balances.parallelStream().flatMap(balance -> {

            AppBalanceVO appBalanceVO = new AppBalanceVO();
            ToolUtil.copyProperties(balance, appBalanceVO);
            return Stream.of(appBalanceVO);

        }).collect(Collectors.toList()))
        .orElse(null);
    }

    @Override
    public BigDecimal getProfitByUserId(String userId) {

        return Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<Balance>lambdaQuery()
                .eq(Balance::getAddOrSubtractTypeEnum, AddOrSubtractTypeEnum.ADD)
                .eq(Balance::getBooleanReturnMoney, BooleanTypeEnum.NO)
                .eq(Balance::getBalanceType, BalanceTypeEnum.SHARE_MONEY)
                .eq(Balance::getCreateBy, userId))))
        .map(balances -> balances.parallelStream().map(Balance::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add))
        .orElse(new BigDecimal(0));
    }

    @Override
    public BigDecimal getOrderFreezeMoney(String userId) {

        return Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<Balance>lambdaQuery()
        .eq(Balance::getCreateBy, userId)
        .eq(Balance::getBooleanReturnMoney, BooleanTypeEnum.NO)
        .eq(Balance::getFreezeMoney, BooleanTypeEnum.YES)
        .eq(Balance::getAddOrSubtractTypeEnum, AddOrSubtractTypeEnum.ADD)
        .orderByDesc(Balance::getCreateTime))))
        .map(balances -> balances.parallelStream().filter(balance -> orderService.judgeOrderFreeze(balance.getOrderId()))
        .map(Balance::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add))
        .orElse(new BigDecimal(0));
    }


    @Override
    public void resolveReturnBalance(OrderAfterTypeEnum orderAfterTypeEnum, String orderId, BigDecimal actualRefundMoney) {


        Optional.ofNullable(orderService.getById(orderId)).flatMap(order -> Optional.ofNullable(ToolUtil.setListToNul(this.list(Wrappers.<Balance>lambdaQuery()
                .eq(Balance::getAddOrSubtractTypeEnum, AddOrSubtractTypeEnum.ADD)
                .eq(Balance::getBooleanReturnMoney, BooleanTypeEnum.NO)
                .eq(Balance::getOrderId, order.getId()))))).ifPresent(balances -> {

                    Order order = orderService.getById(orderId);

                    //1 平台收入为 0
                    ThreadPoolUtil.getPool().execute(() -> {

                        REENTRANT_LOCK.lock();

                        try {
                            while (nextOne != 1) {

                                c1.await();
                            }

                            Optional.ofNullable(profitDetailService.list(Wrappers.<ProfitDetail>lambdaQuery()
                                    .eq(ProfitDetail::getOrderId, orderId)
                                    .eq(ProfitDetail::getProfitDetailEnum, ProfitDetailEnum.PLATFORM)))
                                    .ifPresent(profitDetails -> {

                                        profitDetails.parallelStream().forEach(profitDetail -> {

                                            profitDetail.setProfitMoney(new BigDecimal(0));
                                            profitDetailService.updateById(profitDetail);
                                        });

                                        log.info(Thread.currentThread().getName() + "执行完成: 平台收入");
                                    });

                            nextOne = 2;
                            c2.signalAll();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            REENTRANT_LOCK.unlock();
                        }

                    });

                    //2 处理所有分佣退回
                    ThreadPoolUtil.getPool().execute(() -> {

                        REENTRANT_LOCK.lock();

                        try {

                            while (nextOne != 2) {

                                c2.await();
                            }

                            Optional.ofNullable(ToolUtil.setListToNul(balances.stream().filter(balance -> balance.getBalanceType().equals(BalanceTypeEnum.SHARE_MONEY))
                                    .collect(Collectors.toList()))).ifPresent(balancesShares -> {

                                        balancesShares.parallelStream().forEach(balance -> Optional.ofNullable(userService.getById(balance.getCreateBy())).ifPresent(relationUser -> {


                                            //2.2 设置为退款金额 来满足冻结金的返还
                                            balance.setBooleanReturnMoney(BooleanTypeEnum.YES)
                                                    .setFreezeMoney(BooleanTypeEnum.NO);
                                            this.updateById(balance);

                                            if (!order.getCreateBy().equals(relationUser.getId())) {

                                                //2.2 记录明细
                                                Balance balanceShareUser = new Balance();
                                                balanceShareUser.setTitle(orderDetailService.getBalanceTitleByOrder(order) + "(佣金退回)")
                                                        .setAddOrSubtractTypeEnum(AddOrSubtractTypeEnum.SUB)
                                                        .setPrice(balance.getPrice())
                                                        .setOrderId(order.getId())
                                                        .setCreateBy(relationUser.getId());
                                                this.save(balanceShareUser);
                                            }

                                            //2.4 处理退款资金明细
                                            Optional.ofNullable(profitDetailService.list(Wrappers.<ProfitDetail>lambdaQuery()
                                                    .eq(ProfitDetail::getOrderId, balance.getOrderId())
                                                    .eq(ProfitDetail::getAddOrSubtractType, AddOrSubtractTypeEnum.ADD)
                                                    .ne(ProfitDetail::getProfitDetailEnum, ProfitDetailEnum.PLATFORM)
                                                    .eq(ProfitDetail::getCreateBy, balance.getCreateBy())))
                                                    .ifPresent(profitDetails -> profitDetails.parallelStream().forEach(profitDetail -> {
                                                        profitDetail.setProfitMoney(new BigDecimal(0));
                                                        profitDetailService.updateById(profitDetail);
                                                    }));
                                        }));


                                        //处理推荐人佣金问题
                                       Optional.ofNullable(ToolUtil.setListToNul(balancesShares.parallelStream().filter(balance -> !order.getCreateBy().equals(balance.getCreateBy()))
                                               .collect(Collectors.toList()))).ifPresent(balancesRelations -> {

                                                   //总共的退款金额
                                                   BigDecimal returnStoreMoney = balancesRelations.parallelStream().map(Balance::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);


                                                   Optional.ofNullable(userService.getById(balancesRelations.get(0).getCreateBy())).ifPresent(relationUsers -> {

                                                       //1. 推荐人可能是商家
                                                       if (ObjectUtil.equal(order.getUserId(), relationUsers.getId())) {

                                                           //设置原子变量
                                                           balance.set(returnStoreMoney.doubleValue());
                                                       }else {

                                                           relationUsers.setBalance(relationUsers.getBalance().subtract(returnStoreMoney));
                                                           userService.updateById(relationUsers);
                                                           log.info("当前用户余额是" + relationUsers.getBalance());

                                                       }
                                                   });

                                       });

                                      log.info(Thread.currentThread().getName() + "执行完成: 佣金退回");
                            });

                            nextOne = 3;
                            c3.signalAll();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {

                            REENTRANT_LOCK.unlock();
                        }
                    });

                    //3. 处理消费者逻辑
                    ThreadPoolUtil.getPool().execute(() -> {

                        REENTRANT_LOCK.lock();
                        try {

                            while (nextOne != 3) {

                                c3.await();
                            }

                            Optional.ofNullable(userService.getById(order.getCreateBy())).ifPresent(userCustom -> {

                                //3.1 记录余额明细
                                Balance balanceUser = new Balance();
                                balanceUser.setAddOrSubtractTypeEnum(AddOrSubtractTypeEnum.ADD)
                                        .setBooleanReturnMoney(BooleanTypeEnum.YES);

                                ProfitPercentDetailVo profitPercentDetailVo = profitPercentService.getProfitPercentDetailVo(userService.getById(order.getUserId()).getClassId(), order.getCreateBy());

                                if (ToolUtil.isEmpty(actualRefundMoney)) {

                                    //申请退款金额
                                    BigDecimal returnMoney = orderAfterSaleService.getOrderAfterSaleReturnMoney(orderId);

                                    //3.2.1 更新消费者账户余额
                                    if (OrderAfterTypeEnum.ONLINE_RETURN.equals(orderAfterTypeEnum)) {

                                        balanceUser.setTitle(orderDetailService.getBalanceTitleByOrder(order) + " (线上退款)")
                                                .setPrice(returnMoney.multiply(new BigDecimal("0.94")));

                                        //消费者实际得到的是 除了自己佣金之外的钱
                                        userCustom.setBalance(userCustom.getBalance().add(returnMoney.multiply(new BigDecimal("0.94"))));
                                        userService.updateById(userCustom);
                                    }else {

                                        //线下退款消费者实际得到的是除了自己的佣金之外的佣金退还的钱
                                        log.info("当前部分退款的用佣金比例:" + profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent()));

                                        balanceUser.setTitle(orderDetailService.getBalanceTitleByOrder(order) + "（线下退款佣金退回)")
                                                .setPrice(returnMoney.multiply(profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent())));

                                        userCustom.setBalance(userCustom.getBalance().add(returnMoney.multiply(profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent()))));
                                        userService.updateById(userCustom);
                                    }

                                    //3.3.1 资金流向明细
                                    Optional.ofNullable(profitDetailService.list(Wrappers.<ProfitDetail>lambdaQuery()
                                            .eq(ProfitDetail::getOrderId, order.getId())
                                            .eq(ProfitDetail::getAddOrSubtractType, AddOrSubtractTypeEnum.SUB)
                                            .eq(ProfitDetail::getCreateBy, userCustom.getId())))
                                            .ifPresent(profitDetails -> profitDetails.parallelStream().forEach(profitDetail -> {

                                                profitDetail.setProfitMoney(profitDetail.getProfitMoney().add(returnMoney));
                                                profitDetailService.updateById(profitDetail);
                                            }));

                                } else {

                                    log.info("当前部分退款的用佣金比例:" + profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent()));

                                    balanceUser.setPrice(actualRefundMoney.add(orderService.getCurrentReturnMoney(order)
                                            .multiply(profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent()))));

                                    //3.2.2 消费者增加余额

                                    if (OrderAfterTypeEnum.ONLINE_RETURN.equals(orderAfterTypeEnum)) {

                                        balanceUser.setTitle(orderDetailService.getBalanceTitleByOrder(order) + " (线上退款)");
                                        userCustom.setBalance(userCustom.getBalance().add(actualRefundMoney.add(orderService.getCurrentReturnMoney(order)
                                                .multiply(profitPercentDetailVo.getPlatformPercent().add(profitPercentDetailVo.getPresenterPercent())))));
                                        userService.updateById(userCustom);
                                    }else {

                                        balanceUser.setTitle(orderDetailService.getBalanceTitleByOrder(order) + " (线下退款)");
                                    }

                                    //3.3.2资金流向明细
                                    Optional.ofNullable(profitDetailService.getOne(Wrappers.<ProfitDetail>lambdaQuery()
                                            .eq(ProfitDetail::getOrderId, order.getId())
                                            .eq(ProfitDetail::getCreateBy, userCustom.getId())
                                            .orderByDesc(ProfitDetail::getCreateTime)
                                            .last("limit 1")))
                                            .ifPresent(profitDetail -> {

                                                profitDetail.setProfitMoney(profitDetail.getProfitMoney().add(actualRefundMoney));
                                                profitDetailService.updateById(profitDetail);

                                            });
                                }

                                balanceUser.setCreateBy(order.getCreateBy());

                                this.save(balanceUser);

                                log.info(Thread.currentThread().getName() + "执行完成: 消费者处理");
                            });

                            nextOne = 4;
                            c4.signalAll();

                        } catch (InterruptedException e) {

                            e.printStackTrace();
                        }finally {

                            REENTRANT_LOCK.unlock();
                        }
                    });


                    //4. 处理商家
                    ThreadPoolUtil.getPool().execute(() -> Optional.ofNullable(userService.getById(order.getUserId())).ifPresent(store -> {

                        REENTRANT_LOCK.lock();

                        try {

                            while (nextOne != 4) {

                                c4.await();
                            }

                            store.setBalance(store.getBalance().subtract(BigDecimal.valueOf(balance.doubleValue())));
                            log.info("当前门店余额更新成功！" + store.getBalance());

                            //4.1 记录余额明细
                            Balance balanceStore = new Balance();
                            balanceStore.setAddOrSubtractTypeEnum(AddOrSubtractTypeEnum.SUB);

                            if (ObjectUtil.equal(OrderAfterTypeEnum.ONLINE_RETURN, orderAfterTypeEnum)) {

                                balanceStore.setTitle(orderDetailService.getBalanceTitleByOrder(order) + "(线上退款)");
                            }else {

                                balanceStore.setTitle(orderDetailService.getBalanceTitleByOrder(order) + "(线下退款)");
                            }


                            //4.2 资金流向
                            ProfitDetail profitDetailStore = profitDetailService.getOne(Wrappers.<ProfitDetail>lambdaQuery()
                                    .eq(ProfitDetail::getOrderId, order.getId())
                                    .eq(ProfitDetail::getProfitDetailEnum, ProfitDetailEnum.STORE)
                                    .eq(ProfitDetail::getCreateBy, order.getUserId())
                                    .orderByDesc(ProfitDetail::getCreateTime)
                                    .last("limit 1"));


                            if (ToolUtil.isEmpty(actualRefundMoney)) {

                                //门店当前收入
                                BigDecimal storeIncomeMoney = storeIncomeService.getStoreIncomeByOrderId(order
                                        .getUserId(), order.getId());

                                if (OrderAfterTypeEnum.ONLINE_RETURN.equals(orderAfterTypeEnum)) {

                                    //门店减少保证金
                                    store.setDepositMoney(store.getDepositMoney().subtract(storeIncomeMoney));
                                }

                                //余额明细设置价格
                                balanceStore.setPrice(storeIncomeMoney);

                                if (ToolUtil.isNotEmpty(profitDetailStore)) {
                                    profitDetailStore.setProfitMoney(new BigDecimal(0));
                                }

                                //4.3 更新退款详情
                                OrderAfterSale orderAfterSale = orderAfterSaleService.getOne(Wrappers.<OrderAfterSale>lambdaQuery()
                                        .eq(OrderAfterSale::getOrderId, order.getId()));
                                orderAfterSale.setActualRefundMoney(storeIncomeMoney);
                                orderAfterSaleService.updateById(orderAfterSale);


                                //4.4 处理商家收入退款
                                Optional.ofNullable(storeIncomeService.getOne(Wrappers.<StoreIncome>lambdaQuery()
                                        .eq(StoreIncome::getOrderId, order.getId())
                                        .eq(StoreIncome::getCreateBy, order.getUserId())))
                                        .ifPresent(storeIncome -> {

                                            storeIncome.setIncomeMoney(new BigDecimal(0));
                                            storeIncomeService.updateById(storeIncome);
                                        });
                            } else {

                                if (OrderAfterTypeEnum.ONLINE_RETURN.equals(orderAfterTypeEnum)) {
                                    //门店余额
                                    store.setDepositMoney(store.getDepositMoney().subtract(actualRefundMoney));
                                }

                                //余额明细
                                balanceStore.setPrice(actualRefundMoney);

                                if (ToolUtil.isNotEmpty(profitDetailStore)) {

                                    profitDetailStore.setProfitMoney(profitDetailStore.getProfitMoney().subtract(actualRefundMoney));
                                }

                                //4.5 处理门店收入
                                Optional.ofNullable(storeIncomeService.getOne(Wrappers.<StoreIncome>lambdaQuery()
                                        .eq(StoreIncome::getOrderId, order.getId())
                                        .eq(StoreIncome::getCreateBy, order.getUserId())))
                                        .ifPresent(storeIncome -> {

                                            storeIncome.setIncomeMoney(storeIncome.getIncomeMoney().subtract(actualRefundMoney));
                                            storeIncomeService.updateById(storeIncome);
                                        });
                            }

                            //更新门店
                            userService.updateById(store);


                            //插入门店余额明细
                            balanceStore.setCreateBy(order.getUserId());
                            this.save(balanceStore);

                            //更新资金流向明细
                            if (ToolUtil.isNotEmpty(profitDetailStore)) {

                                profitDetailService.updateById(profitDetailStore);
                            }

                            log.info(Thread.currentThread().getName() + "执行完成: 商家处理");

                            nextOne = 1;
                            c1.signalAll();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {

                            REENTRANT_LOCK.unlock();
                        }
                    }));
        });
    }

    @Override
    public BalanceCountVo getBalanceCount(String storeId) {


        List<String> orderIds;

        if (ToolUtil.isNotEmpty(storeId)) {

            orderIds = orderService.list(Wrappers.<Order>lambdaQuery().eq(Order::getUserId, storeId)).parallelStream()
                    .map(Order::getId).collect(Collectors.toList());

            //如果商家没有订单，不能让他看平台的订单，所以orderIds不能为空，我默认价格id,
            if (orderIds.size() == 0){

                orderIds.add("00000000");
            }

        }else {

            orderIds = orderService.list().parallelStream().map(Order::getId).collect(Collectors.toList());

        }

        List<Balance> balances = this.list(Wrappers.<Balance>lambdaQuery()
                .in(ToolUtil.isNotEmpty(orderIds),Balance::getOrderId, orderIds)
                .eq(Balance::getAddOrSubtractTypeEnum, AddOrSubtractTypeEnum.ADD)
                .eq(Balance::getBooleanReturnMoney, BooleanTypeEnum.NO)
                .eq(Balance::getBalanceType, BalanceTypeEnum.SHARE_MONEY));

        BalanceCountVo balanceCountVo = new BalanceCountVo();

        // TODO: 2020/5/14 0014  日收入
        List<Balance> day = balances.parallelStream()
                .filter(balance ->
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(balance.getCreateTime()).contains(getToday())
                && orderService.judgeOrderFreeze(balance.getOrderId()) )
                .collect(Collectors.toList());
        balanceCountVo.setDayIncome(day.parallelStream().map(Balance::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        // TODO: 2020/5/14 0014  月收入
        List<Balance> month = balances.parallelStream().filter(balance ->
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(balance.getCreateTime()).contains(getMonth())
                && orderService.judgeOrderFreeze(balance.getOrderId())).collect(Collectors.toList());
        balanceCountVo.setMonthIncome(month.parallelStream().map(Balance::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        // TODO: 2020/5/14 0014  年收入
        List<Balance> year = balances.parallelStream().filter(balance ->
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(balance.getCreateTime()).contains(getYear())
               &&  orderService.judgeOrderFreeze(balance.getOrderId())).collect(Collectors.toList());
        balanceCountVo.setYearIncome(year.parallelStream().map(Balance::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        //总收入
        balanceCountVo.setTotalIncome(balances.parallelStream().filter(balance ->  orderService.judgeOrderFreeze(balance.getOrderId()))
                .map(Balance::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        return balanceCountVo;
    }

    /**
     * 当天
     * @return
     */
    public String getToday(){
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }

    /**
     * 当月
     * @return
     */
    public String getMonth(){
        return new SimpleDateFormat("yyyy-MM").format(new Date());
    }

    /**
     * 当年
     * @return
     */
    public String getYear(){
        return new SimpleDateFormat("yyyy").format(new Date());
    }
}